<?php
// +----------------------------------------------------------------------
// | QbtCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 千佰特 <http://www.qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_payment_management\controller;

use think\Controller;
use think\Db;
vendor("pay.alipay.wappay.service.AlipayTradeService");
vendor("pay.alipay.wappay.buildermodel.AlipayTradeWapPayContentBuilder");
vendor("pay.alipay.wappay.buildermodel.AlipayTradeQueryContentBuilder");
vendor("pay.alipay.wappay.buildermodel.AlipayTradeService");

class AliPayController extends Controller
{

    //配置
    private $config;

    function __construct(){
        $info =  Db::name('payment_management')->where("id = 2")->find();
        $config = json_decode($info['config_json'],true);
        $config['app_id'] = $config['appid'];
        $config['gatewayUrl'] = 'https://openapi.alipay.com/gateway.do';
        $config['charset'] = 'UTF-8';
        $this->config = $config;
    }

    /**阿里支付
     * @param $out_trade_no 商户唯一单号
     * @param $subject 订单名称
     * @param $total_amount 付款金额
     * @param string $body 描述
     * @param string $notify_url 异步通知地址
     * @param string $return_url 同步跳转
     * @throws \Exception
     */
    public function pay($data){
        if (empty($data['notify_url'])){
            //默认异步通知地址
            $notify_url = 'http://'.$_SERVER['SERVER_NAME'].cmf_plugin_url('QbtPaymentManagement://AliPay/notify');
        }
        if (empty($data['return_url'])){
            //默认同步跳转地址
            $return_url = '';
        }

        //超时时间
        $timeout_express="1m";

        $payRequestBuilder = new \AlipayTradeWapPayContentBuilder($data['pay_type']);
        $payRequestBuilder->setBody($data['body']);
        $payRequestBuilder->setSubject($data['subject']);
        $payRequestBuilder->setOutTradeNo($data['order']);
        $payRequestBuilder->setTotalAmount($data['money']);
        $payRequestBuilder->setTimeExpress($timeout_express);

        $payResponse = new \AlipayTradeService($this->config);
        if ($data['pay_type'] == 'pagePay'){
            //电脑网站支付
            $response = $payResponse->pagePay($payRequestBuilder,$return_url,$notify_url);
            return $response;
        }
        if ($data['pay_type'] == 'wapPay') {
            //手机网站支付
            $result=$payResponse->wapPay($payRequestBuilder, $return_url,$notify_url);
            return;
        }
    }

    /**回调函数
     * @throws \Exception
     */
    public function notify()
    {
        $arr=$_GET;
        $alipaySevice = new \AlipayTradeService($this->config);
        $alipaySevice->writeLog(var_export($arr,true));
        $result = $alipaySevice->check($arr);
//        if($result) {//验证成功  //2019-02-01 待处理 暂未知验证失败原因 年后处理
            //添加支付日志
            $result = $this->order_query($arr['trade_no']);
            if ($result->trade_status == 'TRADE_SUCCESS'){
                $data['money'] = $arr["total_amount"];
                $data['pay_time'] = strtotime($arr["timestamp"]);
                $data['pay_type'] = 2;
                $data['transaction_id'] = $arr['trade_no']; //支付宝交易号
                $data['order_no'] = $arr['out_trade_no']; //商户订单号
                $data['trade_type'] = '支付宝支付'; //交易类型
                DB::name('payment_log')->insert($data);
                echo "success";
            }
//        }else {
//            //验证失败
//            echo "fail";
//        }
    }

    /**查询订单
     * @param $transaction_id 支付宝交易号
     * @return
     * @throws \Exception
     */
    private function order_query($transaction_id){
        $RequestBuilder = new \AlipayTradeQueryContentBuilder();
        $RequestBuilder->setTradeNo($transaction_id);
        $Response = new \AlipayTradeService($this->config);
        $result=$Response->Query($RequestBuilder);
        return $result;
    }
}
